package com.itcoon.cloud.framework.utils;/**
 * @author Athric Yu
 * 2024/11/29
 **/

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 *
 *
 * @author Athric Yu
 * 2024/11/29
 **/
public class JsonUtils {

    private static ObjectMapper getObjectMapper(){
        return SpringUtils.getBean(ObjectMapper.class);
    }

    public static String writeToJson(Object obj){
        try {
            return getObjectMapper().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T readFromJson(String json, Class<T> clazz){
        try {
            return getObjectMapper().readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T readFromJson(String json, TypeReference<T> typeReference){
        try {
            return getObjectMapper().readValue(json, typeReference);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
